<template>
    <view class="page-messages">
        <image class="home-bg" :src="getImgUrl('home-bg.png')"></image>
        <view class="content">
            <view class="content-header">
                <view class="header-left" @click="gotoOtherMiniProgram">{{ config.miniProgramName }}</view>
                <view class="user-info">
                    <u-avatar :src="user.avatar" size="150" v-if="user.avatar"></u-avatar>
                    <image class="tanbaishuo" :src="getImgUrl('tanbaishuo.png?t=1')"></image>
                </view>
                <view class="header-right" @click="showExplain = true">联系客服</view>
            </view>
            <view class="my-info">
                <view class="name">{{ config.messageTips }}</view>
                <!-- <view class="other">来对我说句悄悄话吧</view> -->
            </view>
            <template v-if="!requestFlag">
                <view class="messages" v-if="list.length > 0">
                    <scroll-view
                        :scroll-top="scrollTop"
                        scroll-y="true"
                        class="scroll-Y"
                        style="height: calc(100vh - 660rpx);"
                        @scrolltolower="getMoreMessage"
                    >
                        <message
                            v-for="(item, index) in list"
                            :key="index"
                            :message="item"
                            :isSelf="isSelf"
                            :user="user"
                            :top="index === 0 ? 54 : 0"
                            :flag="releaseFlag"
                            @clickReply="handleReply(item, index)"
                            @clickClose="handleClose(item, index)"
                            @pay="pay"
                        ></message>
                    </scroll-view>
                </view>
                <view class="empty" v-else>
                    还没有好友向你提问 请点击下方按钮分享到朋友圈
                </view>
            </template>
        </view>
        <view class="buttons-container">
            <template v-if="list.length > 0 || !isSelf">
                <view class="button button-l" @click="handClickLeft">
                    <text>{{ isSelf ? (releaseFlag ? '邀请留言' : '查看匿名者') : '说悄悄话' }}</text>
                </view>
                <view class="button button-r" @click="handClickRight">
                    <text>{{ isSelf ? '再玩一次' : '我也要玩' }}</text>
                </view>
            </template>
            <view class="button button-c" v-else @click="handClickRight">
                <text style="color:#ffffff">分享到朋友圈</text>
            </view>
            <!-- <button open-type="share">分享</button> -->
        </view>
        <u-popup v-model="showExplain" mode="center" width="640rpx" height="467px" border-radius="16">
            <view class="explain-content">
                <view class="title">特别说明</view>
                <view class="content">
                    <view v-for="(item, index) in explainList" :key="index">{{ item }}</view>
                </view>
                <view class="other">
                    反馈问题、获得更多好玩的小程序，请添加小姐姐微信号：<text style="color:#E35353">{{ weixinhao }}</text>
                </view>
                <view class="button-container">
                    <view class="copy-weixin-button" @click="copyWeixin">点击复制微信号</view>
                    <!-- <u-button :custom-style="customStyle" type="primary" @click="copyWeixin">点击复制微信号</u-button> -->
                </view>
            </view>
        </u-popup>
        <u-popup v-model="showPublic" negative-top="200rpx" mode="center" width="640rpx" border-radius="16">
            <view class="qiaoqiaohua" style="height: 100%;">
                <view class="close-button" @click="showPublic = false">
                    <u-icon name="close-circle-fill" color="#F79090" size="50"></u-icon>
                </view>
                <view class="qiaoqiaohua-input">
                    <u-input
                        v-model="qiaoqiaohua"
                        type="textarea"
                        :border="false"
                        :focus="showPublic"
                        :height="96"
                        :maxlength="100"
                        placeholder="请选择或输入你想对TA说的悄悄话，要走心哦～"
                        placeholder-style="color:#ACACAC;font-size:26rpx;"
                        :clearable="false"
                        :fixed="true"
                    />
                </view>
                <view class="qiaoqiaohua-content">
                    <scroll-view scroll-y="true" class="scroll-Y" style="height: 332rpx;">
                        <view class="input-list">
                            <view
                                class="input-item"
                                v-for="(item, index) in defaultInputList"
                                :key="index"
                                :style="{ backgroundColor: item.color }"
                                @click="qiaoqiaohua = item.text"
                                >{{ item.text }}</view
                            >
                        </view>
                    </scroll-view>

                    <view class="button-container">
                        <view class="send-qiaoqiaoghua-button" @click="confirmSend">
                            发送悄悄话
                        </view>
                        <!-- <u-button :custom-style="customStyle2" type="primary" @click="confirmSend">发送悄悄话</u-button> -->
                    </view>
                </view>
            </view>
        </u-popup>
        <u-popup
            v-model="showReply"
            mode="center"
            width="640rpx"
            border-radius="16"
            negative-top="50%"
            @close="clearReplyContent"
        >
            <view class="qiaoqiaohua">
                <view class="close-button" @click.stop="clearReplyContent">
                    <u-icon name="close-circle-fill" color="#F79090" size="50"></u-icon>
                </view>
                <u-input
                    v-model="replyContent"
                    type="textarea"
                    :border="false"
                    :focus="showReply"
                    :maxlength="100"
                    placeholder="请真诚回复朋友的悄悄话哦～（不超过100字）"
                    placeholder-style="color:#ACACAC;font-size:26rpx;"
                    :clearable="false"
                    :auto-height="false"
                />

                <view class="qiaoqiaohua-content">
                    <view class="send-reply-button" @click="confirmSendReply">
                        回复内容
                    </view>
                </view>
            </view>
        </u-popup>
        <u-modal
            class="delete-container"
            v-model="showDelete"
            content="确定删除该留言"
            :show-cancel-button="true"
            @confirm="confirmDelete"
            @cancel="showDelete = false"
        ></u-modal>
        <u-modal
            v-model="showConfirmPay"
            :content="config.payBtnText"
            border-radius="16"
            :mask-close-able="true"
            @confirm="confirmPay"
            :confirm-style="confirmStyle"
        ></u-modal>
        <u-modal
            v-model="showConfirmPayed"
            content="您已成功查看匿名者，无需重复支付！"
            border-radius="16"
            @confirm="showConfirmPayed = false"
            :confirm-style="confirmStyle"
        ></u-modal>
        <u-modal
            class="delete-container"
            v-model="showLogin"
            content="当前用户未登录"
            confirm-text="微信一键登录"
            cancel-text="取消"
            :show-cancel-button="true"
            @confirm="login"
            @cancel="showLogin = false"
        ></u-modal>

        <u-modal
            class="delete-container"
            v-model="showOpenSettingModal"
            content="检测到您还没有开启订阅消息的权限，是否去设置？"
            :show-cancel-button="true"
            @confirm="confirmOpen"
            @cancel="cancelOpen"
        ></u-modal>
    </view>
</template>

<script>
import Message from '@/components/message';
import storage from '@/common/storage';
import { mapState } from 'vuex';
import getConfigMixin from '@/common/mixins.js';

export default {
    components: {
        Message,
    },
    data() {
        return {
            list: [],
            user: { avatar: '', nickname: '', id: null },
            currentUser: { avatar: '', nickname: '', id: null },
            showExplain: false,
            customStyle: {
                backgroundColor: '#3FCE8D',
                width: '314rpx',
                height: '80rpx',
                fontSize: '30rpx',
            },
            customStyle2: {
                backgroundColor: '#8F63F2',
                height: '80rpx',
                fontSize: '30rpx',
            },
            confirmStyle: {
                // backgroundColor: '#3FCE8D',
                color: '#ffffff',
            },
            showPublic: false,
            qiaoqiaohua: '',
            showReply: false,
            replyContent: '',
            defaultInputList: [],
            activeWisperId: null,
            activeWisperIndex: null,
            showDelete: false,
            currentUserId: '',
            code: '',
            currentPage: 1,
            lastPageFlag: 0,
            showConfirmPay: false,
            isPay: false,
            showConfirmPayed: false,
            showLogin: false,
            requestFlag: true,
            showOpenSettingModal: false
        };
    },
    mixins: [
        getConfigMixin
    ],
    computed: {
        ...mapState(['config']),
        isSelf() {
            const loginUser = storage.get('userInfo');
            if (!loginUser) return false;
            return loginUser.id === Number(this.currentUserId);
        },
        weixinhao() {
            return this.config.weixinhao;
        },
        explainList() {
            return this.config.explain.split('<br>');
        },
        releaseFlag() {
            return this.config.releaseFlag === '0';
        }
    },
    onLoad(options) {
        this.initCurrentUser();
        this.getTemplate();
        // this.login();
        if (options.scene) {
            // 判断是否有scene
            var scene = decodeURIComponent(options.scene); // scene解码
            let arrPara = scene.split(':'); // 拆分scene
            this.currentUserId = arrPara[1];
        } else {
            this.currentUserId = this.currentUser && this.currentUser.id;
        }
        if (options.userId) {
            this.currentUserId = options.userId;
        }
        if (this.currentUserId) {
            this.getMessages();
        }

        uni.login({
            provider: 'weixin',
            success: (res) => {
                this.code = res.code;
            },
        });
    },
    onShow() {
        this.getConfig();
    },
    methods: {
        clearReplyContent() {
            this.showReply = false;
            this.replyContent = '';
        },
        login() {
            this.getUserInfo(() => {
                this.getMessages();
                this.showLogin = false;
                this.$u.toast('登录成功');
            })
        },
        getMessages() {
            uni.showLoading();
            this.requestFlag = true;
            this.$u
                .get('/public/wisper/selectWisperPage', {
                    currentPage: this.currentPage,
                    pageSize: 10,
                    userId: this.currentUserId,
                })
                .then((data) => {
                    uni.hideLoading();
                    this.requestFlag = false;

                    let _data = data && data.list && data.list.items || [];
                    this.list = [...this.list, ..._data];
                    this.lastPageFlag = data && data.list && data.list.lastPageFlag;
                    this.user = { ...data.users };
                });
        },
        getMoreMessage() {
            if (!this.lastPageFlag) {
                this.currentPage++;
                this.getMessages();
            }
        },
        initCurrentUser() {
            this.currentUser = storage.get('userInfo');
        },
        handleReply(item, index) {
            this.activeWisperId = item.id;
            this.showReply = true;
            this.activeWisperIndex = index;
        },
        handleClose(item, index) {
            this.showDelete = true;
            this.activeWisperId = item.id;
            this.activeWisperIndex = index;
        },
        /**
         * 订阅消息
         */
        handleSubscribeMessage(fn) {
            // let _id = [
            //     '-DSijst5L5uCXFbzEDaW35-zFomjPiP-346e8R2IreQ', 'tHhEXNIIpBkx6DEkLKeRDrwxLco621q6fQ-1OMdMaC4',
            //     '7Yvk28cmFHuYNs4Qy6SqwkmXa6QwU5i65CSgQLfABLg'
            // ];
			let _id = [
				'HKLBVFOu1IsnKXKJ5qRJjrwp2E1AVNIpxGuJf46JQrI', 'Gabvm6T1O3sUsA_TC7rbGoAJQ6edRbv18LjGxOJiAiE',
				'UqPHfv0o8qjpge5k39f97st9OHYXHLhSwsWcaRVuX_Y'
			]
            // let isSubscribed = storage.get('isSubscribed') || 0;

            // if (isSubscribed) {
            //     fn && fn();
            //     return;
            // }

            uni.requestSubscribeMessage({
                tmplIds: _id,
                success: (res) => {
                    console.log(res,'res')
                    let templateId = _id.filter(i => res[i] === 'accept');
                    if( templateId.length ) {
                        this.getUserInfo(() => {
                            this.$u.post('/public/subscribe/addSubscribe', {
                                templateId
                            }).then(() => {
                                storage.set('isSubscribed', 1);
                            })

                            fn && fn();
                        });
                    }
                },
                fail: (err) => {
                    console.log(err,'requestSubscribeMessage err')
                    if (err.errCode === 20004) {
                        // 20004:用户关闭了主开关，无法进行订阅,引导开启
                        this.showOpenSettingModal = true;
                    }
                }
            })
        },

        confirmOpen() {
            uni.openSetting({
                success: (res) => {

                }
            })
        },

        cancelOpen() {
            this.showOpenSettingModal = false;
            this.$u.toast('订阅失败');
        },

        handClickLeft() {
            if (!this.currentUser?.id) {
                this.showLogin = true;
                return;
            }

            if (this.releaseFlag) {
                this.$u.route({
                    url: '/pages/index/create',
                    type: 'reLaunch',
                });
                return;
            }

            this.handleSubscribeMessage(() => {
                if (!this.isSelf) {
                    this.showPublic = true;
                } else {
                    console.log(this.currentUser);
                    if (this.currentUser.isPay) {
                        this.showConfirmPayed = true;
                    } else {
                        this.pay();
                    }
                }
            });
        },
        handClickRight() {
            if (!this.currentUser?.id) {
                this.showLogin = true;
                return;
            }

            this.handleSubscribeMessage(() => {
                this.$u.route({
                    url: '/pages/index/create',
                    type: 'reLaunch',
                });
            });
        },
        pay() {
            if (this.isSelf) {
                this.showConfirmPay = true;
            }
        },
        confirmPay() {
            const systemInfo = uni.getSystemInfoSync();
            if (
                (systemInfo.platform === 'ios' && this.config.iosPayFlag === '0') ||
                (systemInfo.platform === 'android' && this.config.andriodPayFlag === '0')
            ) {
                this.showConfirmPay = false;
                return;
            }

            this.$u.post('/public/wisper/wx/pay', {
                amount: this.config.payPrice && Number(this.config.payPrice) || 0.01,
                userId: this.currrentUserId
            }).then((data) => {
                // console.log(data);
                uni.requestPayment({
                    provider: 'wxpay',
                    timeStamp: data.timestamp,
                    nonceStr: data.noncestr,
                    package: data.packageValue,
                    signType: data.signType,
                    paySign: data.paySign,
                    success: () => {
                        this.$u.toast('支付成功');
                        this.$set(this.user, 'isPay', 1);
                        storage.set('userInfo', { ...this.user, isPay: 1 });
                    },
                    fail: (error) => {
                        console.log(error);
                        this.$u.toast('支付失败，请重新支付');
                    },
                });
            });
        },
        confirmSend() {
            if (!this.qiaoqiaohua) {
                this.$u.toast('请输入悄悄话内容');
                return;
            }
            this.$u
                .post('/public/wisper/wisperForUser', { content: this.qiaoqiaohua, guestUserId: this.currentUserId })
                .then(() => {
                    this.$u.toast('发送成功');
                    this.getMessages();
                    this.showPublic = false;
                    this.qiaoqiaohua = '';
                });
        },
        confirmSendReply() {
            if (!this.replyContent) {
                this.$u.toast('请输入回复内容');
                return;
            }
            this.$u.post('/public/wisper/replyWisper', { content: this.replyContent, wisperId: this.activeWisperId }).then(() => {
                this.$u.toast('回复成功');
                // this.getMessages();
                this.list[this.activeWisperIndex].replyList = [{ content: this.replyContent }];
                this.showReply = false;
                this.replyContent = '';
                this.activeWisperId = null;
                this.activeWisperIndex = null;
            });
        },
        confirmDelete() {
            this.$u.post('/public/wisper/removeWisper', { id: this.activeWisperId }).then(() => {
                this.$u.toast('删除成功');
                this.list.splice(this.activeWisperIndex, 1);
                this.showDelete = false;
                this.activeWisperId = null;
                this.activeWisperIndex = null;
            });
        },
        copyWeixin() {
            uni.setClipboardData({
                data: this.weixinhao,
                success: () => {
                    this.$u.toast('复制微信号成功');
                    setTimeout(() => {
                        this.showExplain = false;
                    }, 500);
                },
            });
        },
        getTemplate() {
            this.$u.get('/public/wisper/getWisperTemplates').then((data) => {
                this.defaultInputList = data.map((item, index) => {
                    const colors = ['#F7CECE', '#F8D7B1', '#DBCEF7', '#B0D8F5', '#EAB0F5'];
                    return {
                        text: item.content,
                        color: colors[index % 5],
                    };
                });
            });
        },
        getUserInfo(fn) {
            if (this.currentUser && this.currentUser.avatar) {
                fn && fn();
                return;
            }

            uni.getUserProfile({
                desc: '用户头像展示',
                success: (result) => {
                    // console.log(res.code)
                    console.log(result, 'result');
                    const data = {
                        avatar: result.userInfo.avatarUrl,
                        encryptedData: result.encryptedData,
                        iv: result.iv,
                        jsCode: this.code,
                        nickname: result.userInfo.nickName,
                    };
                    // console.log(data);
                    this.$u.post('/wx/authorize/login', data).then((res) => {
                        storage.set('uid', res.uid);
                        this.$u.get('/public/wisper/getUsersInfo').then((data) => {
                            storage.set('userInfo', data);
                            this.currentUser = data;
                            this.currentUserId = data.id;
                            fn && fn();
                        });
                    });
                },
                fail: (error) => {
                    console.log(error);
                },
            });
        },
        gotoOtherMiniProgram() {
            const link = this.config.miniProgramLink;
            uni.navigateToMiniProgram({ appId: link });
        },
    },
};
</script>

<style lang="scss" scoped>
.page-messages {
    .home-bg {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: -1;
    }
    .content {
        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 52rpx;
            margin-bottom: 56rpx;
            .header-left {
                width: 162rpx;
                height: 72rpx;
                color: #ffffff;
                font-size: 30rpx;
                line-height: 70rpx;
                margin-left: -10rpx;
                text-align: center;
                background: url('https://ftp.bmp.ovh/imgs/2021/05/3dbbd54d35275d87.png') no-repeat;
                background-size: cover;
            }
            .user-info {
                height: 158rpx;
                width: 158rpx;
                background-color: #ffffff;
                border-radius: 50%;
                padding: 4rpx;
                position: relative;
                .tanbaishuo {
                    position: absolute;
					bottom: -12rpx;
					left: 14rpx;
					width: 132rpx;
					height: 46rpx;
                }
            }
            .header-right {
                width: 172rpx;
                height: 72rpx;
                color: #ffffff;
                font-size: 30rpx;
                line-height: 70rpx;
                margin-right: -10rpx;
                text-align: center;
                background: url('https://ftp.bmp.ovh/imgs/2021/05/a909674d1cd80823.png') no-repeat;
                background-size: cover;
            }
        }
        .my-info {
            background: url('https://ftp.bmp.ovh/imgs/2021/05/fc625eb46324c28c.png') no-repeat;
            background-size: cover;
            height: 150rpx;
            margin: 0 32rpx;
            color: #ffffff;
            text-align: center;
            // margin-bottom: 54rpx;
            .name {
                font-weight: 500;
                line-height: 120rpx;
                font-size: 40rpx;
                width: 490rpx;
                margin: 0 auto;
                text-align: center;
            }
            .other {
                font-size: 24rpx;
            }
        }

        .empty {
            color: #ffffff;
            font-size: 32rpx;
            line-height: 44rpx;
            width: 408rpx;
            margin: 0 auto;
            text-align: center;
            margin-top: 200rpx;
        }
    }
    .buttons-container {
        display: flex;
        position: fixed;
        bottom: 72rpx;
        left: 0;
        justify-content: space-between;
        width: 100vw;
        padding: 0 32rpx;
        box-sizing: border-box;
        .button {
            width: 314rpx;
            height: 98rpx;
            line-height: 98rpx;
            text-align: center;
            position: relative;
            font-size: 36rpx;
            font-weight: 500;
        }
        .button-l {
            color: #ffffff;
            background: url('https://ftp.bmp.ovh/imgs/2021/05/36fe4286ddd89ecf.png') no-repeat;
            background-size: cover;
        }
        .button-r {
            color: #f7825f;
            background: url('https://ftp.bmp.ovh/imgs/2021/05/fe59135c0f409ab7.png') no-repeat;
            background-size: cover;
        }
        .button-c {
            color: #000000;
            background: url('https://ftp.bmp.ovh/imgs/2021/05/03de232a23f93579.png') no-repeat;
            background-size: cover;
            width: 608rpx;
            margin: 0 auto;
        }
    }
    .explain-content {
        padding: 56rpx 52rpx 34rpx;
        color: #333333;
        .title {
            font-size: 32rpx;
            font-weight: 500;
            text-align: center;
            margin-bottom: 52rpx;
        }
        .content {
            font-size: 26rpx;
            line-height: 36rpx;
        }
        .other {
            text-align: center;
            margin-top: 52rpx;
            font-size: 28rpx;
            line-height: 40rpx;
            color: #707070;
        }
        .button-container {
            margin-top: 26rpx;
            text-align: center;
            .copy-weixin-button {
                background: url('https://ftp.bmp.ovh/imgs/2021/05/03de232a23f93579.png') no-repeat center;
                background-size: 100% 100%;
                width: 314rpx;
                height: 80rpx;
                line-height: 80rpx;
                font-size: 30rpx;
                color: #ffffff;
                display: inline-block;
            }
        }
    }
    .qiaoqiaohua {
        position: relative;
        display: flex;
        flex-direction: column;
        padding-top: 46rpx;
        &-input {
            height: 188rpx;
            background-color: #f7f7f7;
            padding: 46rpx 40rpx;
            &.reply {
                background-color: #ffffff;
            }
        }
        &-content {
            padding: 32rpx;
            .input-list {
                display: flex;
                flex-wrap: wrap;
                .input-item {
                    padding: 10rpx 28rpx;
                    border-radius: 32rpx;
                    margin-right: 26rpx;
                    margin-bottom: 24rpx;
                    color: #333333;
                    font-size: 24rpx;
                }
            }
            .button-container {
                margin-top: 64rpx;
                .send-qiaoqiaoghua-button {
                    background: url('https://ftp.bmp.ovh/imgs/2021/05/8f447345eb38f3b8.png') no-repeat center;
                    background-size: 100%;
                    height: 98rpx;
                    font-size: 30rpx;
                    text-align: center;
                    line-height: 98rpx;
                    color: #ffffff;
                }
                &.reply {
                    margin-top: 10rpx;
                }
            }
        }
        .close-button {
            position: absolute;
            top: 0;
            right: 0;
        }
    }
    .send-reply-button {
        background: url('https://ftp.bmp.ovh/imgs/2021/05/8f447345eb38f3b8.png') no-repeat center;
        background-size: 100%;
        height: 98rpx;
        font-size: 30rpx;
        text-align: center;
        line-height: 98rpx;
        color: #ffffff;
    }
    /deep/.u-model__footer {
        width: 560rpx;
        background: url('https://ftp.bmp.ovh/imgs/2021/05/03de232a23f93579.png') no-repeat center;
        background-size: 100% 100%;
        margin: 0 auto;
        margin-bottom: 20rpx;
    }
    .delete-container {
        /deep/.u-model__footer {
            width: 560rpx;
            background: none;
            background-size: 100% 100%;
            margin: 0 auto;
            margin-bottom: 20rpx;
        }
    }

    /deep/ .u-input__textarea {
        height: 188rpx;
        padding: 0 40rpx 0 40rpx !important;
        min-height: auto !important;
        box-sizing: border-box;
        overflow-y: scroll;
    }

}
</style>
